/**
 * 老虎机
 * @author rubekid
 */
(function(){
	
	var TYPE_START = 1;
	var TYPE_STOP = 2;
	
	function SlotMachine(options){
		this.init(options);
	}
	
	SlotMachine.prototype = {
		init:function(options){
			this.list = options.list;
			this.highlightClass = options.highlightClass ||"highlight";
			this.highSpeed = options.highSpeed || 24; //告诉运转 单位 格数
			this.lowSpeed = options.lowSpeed || 2; //低速运行 单位 格数
			this.startDuration = options.startDuration || 300 ;// 起始持续时间间隔
			this.subtractDuration = options.subtractDuration || 30; // 时间间隔递减量(加速度)
			
			this.options = options;
			this.addDuration = 15; // 时间间隔增减量(减速度)
			this.isReachMaxSpeed  = false; //是否达到最大速度
			this.minDuration = Math.floor( 1000 / this.highSpeed );
			this.maxDuration = Math.ceil( 1000 / this.lowSpeed );
			this.index = 0;
			this.size = this.list.length;
		},
		start:function(){
			this.duration = 300;
			this.isReachMaxSpeed  = false;
			this.list.removeClass(this.highlightClass);
			this.run(TYPE_START);
		},
		lottery:function(index){
			this._resultIndex = index;
			this.addDuration = Math.ceil((this.maxDuration - this.duration) / this.size);
			this.run(TYPE_STOP);
		},
		run:function(type){
			var _this = this;
			if(this._timeout){
				clearTimeout(this._timeout);
			}
			this.move();
			this._timeout = setTimeout(function(){
				_this.run(type);
			}, this.duration);
			
			if(type == TYPE_STOP){
				if(this._resultIndex == this.index){
					//开启阀门
					this._threshold = true;
				}

				if(this._threshold){
					if(this.duration < this.maxDuration){
						this.duration += this.addDuration;
					}
					else{
						if(this._resultIndex == this.index){
							clearTimeout(this._timeout);
							this._threshold = false;
							if(typeof this.options.afterLottery == "function"){
								this.options.afterLottery();
							}
						}
					}
				}
			}
			else{
				if(this.duration > this.minDuration){
					this.duration -= this.subtractDuration; 
				}
				else{
					if(!this.isReachMaxSpeed){ //达到最高速时触发
						this.duration = this.minDuration;
						if(typeof this.options.afterMaxSpeed == "function"){
							this.options.afterMaxSpeed();
						}
						this.isReachMaxSpeed  = true;
					}
				}
			}
		},
		move:function(){
			this.index ++;
			this.index %=  this.size;
			this.list.removeClass(this.highlightClass);
			this.list.eq(this.index).addClass(this.highlightClass);
			
		}
	};
	
	window.SlotMachine = SlotMachine;
})();